var docRef = app.activeDocument;
var textFrameRef = _getCurrTextFrame();

(function(){
  //@include '../lib/c.js'
  c('selection').filter('textFrames').each(function(){
    setJettaContent(this)
  });
})();

// if (textFrameRef) {
//   setJettaContent(textFrameRef)
// } else {
//   alert('请选择文本')
// }

function setJettaContent(textFrameRef) {
  _setParagraphAttr(textFrameRef, {
    fontIndex: _getFontIndex('HYQiHei-EZS'),
    tracking: 50,
    leading: 1.5,
  })
  _setCharacterAttr(textFrameRef, {
    fontIndex: _getFontIndex('PFDinTextUniversal-Light'),
    scale: 1,
    tracking: 25,
    baselineShift: 0,
  })
}

function _setParagraphAttr(textFrameRef, attr){  
  var textRange = textFrameRef.textRange
  textRange.textFont = app.textFonts[attr.fontIndex];
  textRange.tracking = attr.tracking;
  textRange.autoLeading = false;
  textRange.leading = (attr.size || textRange.size) * attr.leading;
  if(attr.contents) {
    textRange.contents = attr.contents;
  }
  if(attr.top) {
    textRange.top = attr.top;
  }
  if(attr.left) {
    textRange.left = attr.left;
  }
  if(attr.size) { textRange.size = attr.size; }
}

function _setCharacterAttr(textFrameRef, attr) {
  var charCount = textFrameRef.textRange.characters.length;
  for(i=0; i<charCount; i++) {
      var charRef = textFrameRef.textRange.characters[i].contents
      var characterAttributes = textFrameRef.textRange.characters[i].characterAttributes
      var size = characterAttributes.size
      if (__isInCharSet(charRef)) {
          characterAttributes.textFont = app.textFonts[attr.fontIndex];
          characterAttributes.horizontalScale = attr.scale * 100;
          characterAttributes.verticalScale = attr.scale * 100;
          if (attr.tracking) {
            characterAttributes.tracking = attr.tracking;
          }
          characterAttributes.baselineShift = -size * attr.baselineShift;
          // characterAttributes.autoLeading = false;
          // characterAttributes.leading = size * 1.5;
      }
  }
}

function _getCurrTextFrame() {
    var selectedItems = app.activeDocument.selection;
    if ( selectedItems.length > 0 ) {
      if ( selectedItems[0].typename == "TextFrame" ) {
        return selectedItems[0]
      }
    }
        return selectedItems[0]
    return null
  }

  function __isInCharSet(character) {
    var charSet = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-';
    return charSet.indexOf(character) != -1;
  }

  function _getFontIndex(name) {
    var index = 0
    for(var i = 0; i < app.textFonts.length; i++) {
        if(app.textFonts[i].name === name) {
            index = i
            break;
        }
    }
    return index
  }
